package com.objectdraw.client;
import java.net.*;
import java.io.*;


/**
 * This class is responsible for client side communications.  It opens the 
 * clients socket and send messages to the server.
 * 
 * 
 * @author jgulik
 *
 */
public class clientcomm {
	private Socket mySocket;
    private PrintWriter out = null;
    private BufferedReader in = null;
    
    /**
     * Opens a new socket on port 5454.  Initializes the input and output streams.
     * 
     * @param host A string used for the sockets name
     * @throws UnknownHostException
     * @throws IOException
     */
	public clientcomm(String host) throws UnknownHostException, IOException{
		mySocket = new Socket(host, 5454);
		out = new PrintWriter(mySocket.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
	}

	/**
	 * Sends a message to the server.
	 * 
	 * @param msg String that is output on the stream
	 */
	public void sendMessage(String msg){
		System.out.println("sending:"+msg);
		out.println(msg);
	}
	public boolean ready(){
		try {
			return in.ready();
		} catch (IOException e) {
			return false;
		}
	}
	
	/**
	 * 
	 * @return the next line on the input buffer
	 * @throws IOException
	 */
	public String readMessage() throws IOException{
		return in.readLine();
	}

	/**
	 * sends the disconnect message and closes the socket
	 */
	public void close() {
		try {
			sendMessage("disconnect ");
			if(!mySocket.isClosed()){
				mySocket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
